package osmedile.intellij.util.psi;

import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiCodeBlock;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiMethodCallExpression;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiParameterList;
import com.intellij.psi.PsiStatement;
import org.jetbrains.annotations.Nullable;

/**
 * @author Olivier Smedile
 * @version $Id: File Header.java 3 2008-03-11 08:52:55Z osmedile $
 */
public class PsiUtil {


    /**
     * @param psiElt
     *
     * @return the psiParameter of the enclosing method of psiElt
     */
    public static PsiParameter findPsiParameter(PsiElement psiElt) {
        if (psiElt instanceof PsiClass) {
            return null;
        } else if (psiElt instanceof PsiMethod) {
            PsiParameterList psiParameterList = ((PsiMethod) psiElt).getParameterList();
            if (psiParameterList.getParametersCount() > 0) {
                return psiParameterList.getParameters()[0];
            }
            return null;
        } else if (psiElt instanceof PsiParameter) {

            return (PsiParameter) psiElt;
        } else {
            return findPsiParameter(psiElt.getParent());
        }
    }


    /**
     * Return the psiElement of the "super();" or "this();" statement inside the constructor.
     * Return null if method is null, not a constructor or doesn't contains a "super();" or "this();"
     *
     * @param constructor the constructor
     *
     * @return psiElement of the "super();" or "this();" statement inside the constructor
     */
    @Nullable
    public static PsiElement findThisOrSuper(@Nullable PsiMethod constructor) {
        if (constructor == null || !constructor.isConstructor()) {
            return null;
        }
        PsiCodeBlock body = constructor.getBody();
        if (body != null) {
            PsiStatement[] statements = body.getStatements();
            if (statements.length > 0) {
                PsiElement firstChild = statements[0].getFirstChild();
                if (firstChild instanceof PsiMethodCallExpression) {
                    String text = ((PsiMethodCallExpression) firstChild).getMethodExpression().getText();
                    if (text.equals("super")) {
                        return statements[0];
                    } else if (text.equals("this")) {
                        return statements[0];
                    }
                }
            }
        }
        return null;
    }

}
